package io.kiki.stack.netty;

import io.kiki.stack.netty.util.InetSocketAddressUtil;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@Setter
@Getter
@Sharable
public class ServerIdleHandler extends ChannelDuplexHandler {


    @Override
    public void userEventTriggered(final ChannelHandlerContext channelHandlerContext, Object event) throws Exception {
        if (event instanceof IdleStateEvent) {
            try {
                log.warn("Channel idle, close it from server side: {}", InetSocketAddressUtil.parseRemoteAddress(channelHandlerContext.channel()));
                channelHandlerContext.close();
            } catch (Exception e) {
                log.warn("Exception caught when closing Channel in ServerIdleHandler.", e);
            }
        } else {
            super.userEventTriggered(channelHandlerContext, event);
        }
    }
}
